﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common.Extensions
{
    public static class AddSwaggerExt
    {
        public static void AddSwaggerExtensions(this WebApplicationBuilder builder)
        {
            builder.Services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo()
                {
                    Version = "v1",
                    Title = "WebApi文档说明",
                    Description = "框架说明文档",
                    Contact = new OpenApiContact()
                    {
                        Name = "wja",
                        Email = "1258399119@qq.com"
                    }
                });

                // 添加 Swagger 注释功能
                var path = AppContext.BaseDirectory;
                var xmlPath = Path.Combine(path, "WebApi.xml");
                c.IncludeXmlComments(xmlPath, true);

                var xmlModelPath = Path.Combine(path, "DbModel.xml");
                c.IncludeXmlComments(xmlModelPath);

                // 开启小锁
                // c.OperationFilter<AddResponseHeaderFilder>
                #region 支持jwt token授权

                //添加安全定义--配置支持token授权机制
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = "请输入token,格式为 Bearer xxxxxxxx（注意中间必须有空格）",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey,
                    BearerFormat = "JWT",
                    Scheme = "Bearer"
                });
                //添加安全要求
                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference =new OpenApiReference()
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id ="Bearer"
                            }
                        },
                        new string[]{ }
                    }
                });

                #endregion
            });
        }

        public static void UseSwaggerExt(this WebApplication app)
        {
            app.UseSwagger();
            app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "v1"));
        }
    }
}
